package springinpractice.ch1.service;

import java.math.BigDecimal;
import java.util.*;
import springinpractice.ch1.model.Account;
import springinpractice.ch1.dao.AccountDao;

/*
 * @author	Willie Wheeler, John Wheeler and Zeeshan Maqbool
 * Book		'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

public class AccountService
{
	private AccountDao accountDao;

	public void setAccountDao(AccountDao accountDao)
	{
		this.accountDao = accountDao;
	}

	public List<Account> findDelinquentAccounts() throws Exception
	{
		List<Account> delinquentAccounts = new ArrayList<Account>();
		List<Account> accounts = accountDao.findAll();
		Date thirtyDaysAgo = daysAgo(30);
		for (Account account : accounts)
		{
			int balanceDiffVal = account.getBalance().compareTo(BigDecimal.ZERO);
			boolean owesMoney = balanceDiffVal > 0;
			int timeDiffVal = account.getLastPaidOn().compareTo(thirtyDaysAgo);
			boolean thirtyDaysLate = timeDiffVal <= 0;
			if (owesMoney && thirtyDaysLate)
			{
				delinquentAccounts.add(account);
			}
		}
		return delinquentAccounts;
	}

	private static Date daysAgo(int days)
	{
		GregorianCalendar gc = new GregorianCalendar();
		gc.add(Calendar.DATE, -days);
		return gc.getTime();
	}
}
